<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>首页示例</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

    <link rel="icon" href="img/favicon.ico">
    <style>
        body {
            background-color: #f5f5f5;
            color: #333;
            margin: 0;
            padding: 0;
        }

        .header {
            color: white;
            text-align: center;
            line-height: 60px;
            padding: 0;
        }

        .el-menu {
            justify-content: center;
            display: flex;
        }

        .title-bar {
            color: rgb(0, 0, 0);
            padding: 10px;
            text-align: center;
            display: flex;
            justify-content: flex-end;
            align-items: center;
        }

        .title-bar h3 {
            padding: 0;
            margin: 0;
        }

        .product-display {
            display: flex;
            justify-content:  flex-start;
            padding-left: 15%;
            flex-wrap: wrap;
            align-content: center;
        }

        .product-card {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            text-align: center;
            margin: 10px;
            flex: 0 1 calc(33.333% - 20px);
            box-sizing: border-box;
            transition: transform 0.3s ease;
            max-width: 300px;
        }

        .product-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
            border: 1px red solid;
        }

        .productImg {
            height: 200px;
        }

        .product-image {
            width: 100%;
            height: 100%;
            object-fit: contain;
            background-position: center center;
            margin-bottom: 10px;
            border-radius: .08rem .08rem 0 0;
        }

        .product-info {
            text-align: left;
            word-wrap: break-word;
        }

        .product-name {
            font-size: 18px;
            font-weight: bold;
            margin: 5px 0;
            text-align: center;
        }

        .product-description {
            font-size: 14px;
            color: #666;
            margin: 5px 0;
        }

        .product-price {
            font-size: 16px;
            color: #e74c3c;
            margin: 5px 0;
        }

        .product-stock {
            font-size: 14px;
            color: #2ecc71;
            margin: 5px 0;
        }

        @media (max-width: 768px) {
            .product-card {
                flex: 1 1 calc(50% - 20px);
            }
        }

        @media (max-width: 480px) {
            .product-card {
                flex: 1 1 100%;
            }
        }

        .wheel-container {
            position: relative;
            width: 300px;
            height: 300px;
            margin: 60px auto;
        }

        .wheel {
            width: 100%;
            height: 100%;
            border-radius: 50%;
            border: 5px solid #ccc;
            position: relative;
            overflow: hidden;
            transition: transform 4s cubic-bezier(0.33, 1, 0.68, 1);
        }

        .segment {
            position: absolute;
            width: 50%;
            height: 50%;
            background-color: #f5f5f5;
            border: 1px solid #ddd;
            transform-origin: 100% 100%;
            clip-path: polygon(0 0, 100% 0, 100% 100%);
        }

        .segment span {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            transform-origin: 0 0;
            font-size: 14px;
        }

        /* 悬浮按钮样式 */
        .floating-button {
            /* position: fixed; */
            right: 20px;
            background-color: #0abdfe;
            color: white;
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
            margin: 10px 0;
        }

        .button-container {
            position: fixed;
            top: 50%;
            right: 20px;
            transform: translateY(-50%);
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .dialog {
            width: 100%;
            float: left;
        }

        .send_msg {
            background-color: #f8f8f8;
            word-wrap: break-word;
            border-radius: 10px;
            padding: 15px;
            margin: 30px;
            position: relative;
            float: left;
        }

        .send_msg::before {
            content: "";
            position: absolute;
            top: 50%;
            left: -10px;
            /* 调整三角形的位置使底部紧贴在盒子的左边 */
            transform: translateY(-50%);
            width: 0;
            height: 0;
            border-top: 10px solid transparent;
            border-bottom: 10px solid transparent;
            border-right: 10px solid #f8f8f8;
        }

        .recive_msg::before {
            content: "";
            position: absolute;
            right: -20px;
            /* 使三角形指向右侧 */
            top: 50%;
            transform: translateY(-50%);
            border-width: 10px;
            border-style: solid;
            border-color: transparent transparent transparent #ccf3f2;
        }

        .recive_msg {
            position: relative;
            background-color: #ccf3f2;
            word-wrap: break-word;
            border-radius: 10px;
            padding: 15px;
            margin: 30px;
            float: right;
        }

        .message_box {
            width: 100%;
            height: 100%;
        }

        .prize_box {
            width: 300px;
            height: 300px;
            background-image: url("img/konglp.jpeg");
            background-repeat: no-repeat;
            background-position: center center;
            background-size: cover;
            position: relative;
            transition: transform 4s ease-out;
        }

        .img_box {
            width: 65px;
            height: 80px;
            position: absolute;
            top: 50%;
            left: 50%;
            transition: transform 4s ease-out;
            z-index: 999;
        }

        .prize_one {
            position: absolute;
            top: 20%;
            left: 45%;
        }

        .prize_six {
            position: absolute;
            top: 35%;
            left: 20%;
        }

        .prize_tow {
            position: absolute;
            top: 35%;
            right: 20%;
        }

        .prize_four {
            position: absolute;
            bottom: 20%;
            left: 45%;
        }

        .prize_five {
            position: absolute;
            bottom: 35%;
            left: 20%;
        }

        .prize_three {
            position: absolute;
            bottom: 35%;
            right: 20%;
        }

        .prize_box div {
            font-size: small;
            color: #fe7676;
            font-weight: bold;
        }

        .prize_img {
            width: 30px;
            height: 30px
        }

        .loading-container {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200px;
            /* 确保有足够的高度来显示加载动画 */
        }
    </style>
</head>

<body>
<div id="app">
    <el-container>
        <el-header class="header">
            <el-menu mode="horizontal" background-color="#0abdfe" text-color="#fff" active-text-color="#ffd04b">
                <el-menu-item index="1">关于工厂</el-menu-item>
                <el-menu-item v-if="!isLoggedIn" index="2" @click="goToLogin">登录</el-menu-item>
                <el-menu-item v-else index="4">
                    <el-dropdown class="avatar-container right-menu-item" trigger="click">
                        <div>
                            <img :src="userAvatar" alt="" style="width: 30px; border-radius: 50%;     width: 30px;
      vertical-align: middle;">
                            {{ userName }}
                        </div>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item divided>
                                <span style="display:block;" @click="handlePwdUpdate()">修改密码</span>
                            </el-dropdown-item>
                            <el-dropdown-item divided>
                                <a href="/logout"><span style="display:block;">退出</span></a>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                        <!-- 修改密码标签弹层 -->
                        <div class="add-form">
                            <el-dialog title="修改密码" :visible.sync="dialogFormVisiblePwd">
                                <el-form ref="dataPwdForm" :model="formData" :rules="rules" label-position="right"
                                         label-width="100px">
                                    <el-row>
                                        <el-col>
                                            <el-form-item prop="password">
                                                <el-input type="password" v-model="formData.password"
                                                          auto-complete="off"
                                                          placeholder="密���"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                    <el-row>
                                        <el-col>
                                            <el-form-item prop="confirmPassword">
                                                <el-input type="password" v-model="formData.confirmPassword"
                                                          auto-complete="off"
                                                          placeholder="确认密码"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>
                                </el-form>
                                <div slot="footer" class="dialog-footer">
                                    <el-button @click="dialogFormVisiblePwd = false">取消</el-button>
                                    <el-button type="primary" @click="handlePwd()">确定</el-button>
                                </div>
                            </el-dialog>
                        </div>
                    </el-dropdown>

                </el-menu-item>
                <el-menu-item  index="5" @click="toRecord">中奖记录</el-menu-item>
                <el-menu-item index="3" @click="goToMyOrders">查订单</el-menu-item>
            </el-menu>
        </el-header>

        <el-main>
            <div class="title-bar">
                <h3>产品展示</h3>
                <div style="text-align: right;width: 50%;font-size: x-small;color: gray;cursor: pointer;" >
                    <el-input placeholder="请输入搜索内容"  class="input-with-select" style="width: 50%" v-model="proName">
                        <el-button slot="append" icon="el-icon-search" @click="init()"></el-button>
                    </el-input>
                </div>
            </div>
            <div v-if="loading" class="loading-container">
                <el-spinner type="circle"></el-spinner>
            </div>
            <div v-else>
                <div v-if="products.length === 0" class="no-products-message" style="text-align: center">
                    还没商品捏快去上架吧！
                </div>
                <div v-else class="product-display">
                    <div class="product-card" v-for="product in products" :key="product.id">
                        <div class="productImg">
                            <img :src="product.mainImage" alt="Product Image" class="product-image">
                        </div>
                        <div class="product-info">
                            <h3 class="product-name">{{ product.name }}</h3>
                            <p class="product-description">{{ product.description }}</p>
                            <p class="product-price">价格: ¥{{ product.price }}</p>
                            <p class="product-stock">库存: {{ product.stockQuantity }}</p>
                            <el-button type="primary" @click="buyNow(product.id)">立即购买</el-button>
                        </div>
                    </div>
                </div>
            </div>
            <div style="text-align: right;width: 50%;font-size: x-small;color: gray;cursor: pointer;" ref="scrollEnd">
                <span>已经到底啦~</span>
            </div>

            <div class="title-bar" style="justify-content: center;padding-left: 0;">
                <h3>促销活动</h3>
            </div>
            <el-row>
                <el-col :span="12" style="display: flex; justify-content: center;">
                    <el-card shadow="always" style="width: 220px; cursor: pointer;text-align: center;"
                             @click="startLottery()">
                        <el-button type="text" class="button" @click="startLottery()">立即抽奖，赢取大奖！</el-button>
                    </el-card>
                </el-col>
                <el-col :span="12" style="display: flex; justify-content: center;">
                    <el-card shadow="always" style="width: 220px; cursor: pointer;text-align: center;"
                             @click="startLottery">
                        <el-button type="text" class="button" @click="startLottery()">砸蛋赢大奖！</el-button>
                    </el-card>
                </el-col>
            </el-row>
            <el-row justify="center" type="flex" style="text-align: center;">
                <el-col :span="24">
                    <div class="wheel-container">
                        <div class="prize_box" :style="{transform: `rotate(${roll}deg)`}" v-if="prizeList.length > 0" ref="prizeBox">
                            <div class="prize_one">
                                {{prizeList[0].name}}
                            </div>
                            <div class="prize_tow">
                                {{prizeList[1]?.name ? prizeList[1].name : '谢谢参与'}}
                            </div>
                            <div class="prize_three">
                                {{prizeList[2]?.name ? prizeList[2].name : '谢谢参与'}}
                            </div>
                            <div class="prize_four">
                                {{prizeList[3]?.name ? prizeList[3].name : '谢谢参与'}}
                            </div>
                            <div class="prize_five">
                                {{prizeList[4]?.name ? prizeList[4].name : '谢谢参与'}}
                            </div>
                            <div class="prize_six">
                                {{prizeList[5]?.name ? prizeList[5].name : '谢谢参与'}}
                            </div>
                            <img src="img/zhizheng.png" alt="" srcset="" class="img_box"
                                 :style="{ transform: `translate(-50%, -50%) rotate(-${roll}deg)` }">
                        </div>
                    </div>
                </el-col>
            </el-row>
        </el-main>
        <!-- 悬浮按钮容器 -->
        <div class="button-container">
            <button class="floating-button" @click="openCustomerServiceChat">客服</button>
            <button class="floating-button" @click="openExchangeChat">变现兑换</button>
        </div>

        <el-drawer
                title="中奖记录!"
                :visible.sync="showLottery"
                direction="rtl"
                size="50%">
            <el-table :data="lotteryRecords">
                <el-table-column property="id" label="中奖号" width="150"></el-table-column>
                <el-table-column property="name" label="奖品" width="150"></el-table-column>
                <el-table-column property="isWinning" label="是否中奖" width="200">
                    <template slot-scope="scope">
                        <el-tag size="medium" v-if="scope.row.isWinning === 1">中奖</el-tag>
                        <el-tag type="danger" size="medium" v-else>未中奖</el-tag>
                    </template>
                </el-table-column>
                <el-table-column property="createdAt" label="中奖时间"></el-table-column>
            </el-table>
            <el-pagination background layout="prev, pager, next ,sizes,total" :total="recTotal" :page-size="recordParams.pageSize" :current-page="recordParams.pageNo"
                           @current-change="handlePageChange" :page-sizes="[100, 200, 300, 400]" @size-change="handleSizeChange">
            </el-pagination>
        </el-drawer>

        <!-- 全屏聊天对话框 -->
        <el-dialog :visible.sync="dialogVisible" width="100%" :fullscreen="true">
            <div style="padding: 10px; background-color: #0abdfe; color: white; text-align: center;">
                <span>{{ chatTitle }}</span>
            </div>
            <div style="padding: 10px;">
                <!-- 添加固定高度的容器，并设置overflow-y为auto -->
                <div class="dialog-container"
                     style="height: calc(100vh - 280px); overflow-y: auto; padding-bottom: 20px;">
                    <!-- 聊天内容 -->
                    <div class="dialog" v-for="(item,index) in messageList" :key="item.id">
                        <div :class="item.receiverId === userId? 'send_msg' : 'recive_msg'">
                            <div v-if="item.messageType !== 'img'">{{item.messageText}}</div>
                            <image v-else :src="item.messageText" width="80px" height="80px"></image>
                        </div>
                    </div>
                </div>
                <div
                        style="position: fixed; bottom: 0; width: 100%; padding: 20px; background-color: #fff; border-top: 1px solid #eee;">
                    <div style="max-width: 800px; margin: 0 auto; display: flex; align-items: center;">
                        <el-input placeholder="请输入需要发送的消息" v-model="messageText"
                                  @keyup.enter.native="toSendMessage"
                                  style="margin-right: 10px;"></el-input>
                        <!--                        <el-upload class="avatar-uploader" action="https://www.twiceok.com/feignService/upload"-->
                        <!--                                   :show-file-list="false" :on-success="handleAvatarSuccess"-->
                        <!--                                   :before-upload="beforeAvatarUpload"-->
                        <!--                                   style="margin-right: 10px;">-->
                        <!--                            <img v-if="imageUrl" :src="imageUrl" class="avatar"/>-->
                        <!--                            <el-icon class="icon">-->
                        <!--                                <CirclePlus/>-->
                        <!--                            </el-icon>-->
                        <!--                        </el-upload>-->
                        <el-button type="primary" @click="toSendMessage">发送</el-button>
                    </div>
                </div>
            </div>
        </el-dialog>
    </el-container>
</div>
<script src="../js/vue.js"></script>
<script src="../js/axios-0.18.0.js"></script>
<script src="../plugins/elementui/eindex.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            const validateConfirmPassword = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入确认密码'));
                } else if (value !== this.formData.password) {
                    callback(new Error('两次输入的密码不一致'));
                } else {
                    callback();
                }
            };
            return {
                dialogFormVisiblePwd: false,
                rules: {
                    password: [{required: true, message: "请输入密码", trigger: "blur"}],
                    confirmPassword: [
                        {required: true, message: "请输入确认密码", trigger: "blur"},
                        {validator: validateConfirmPassword, trigger: "blur"}
                    ]
                },
                formData: {},
                avatar: "/img/head_img.png",
                products: [],
                segments: ['奖品1', '奖品2', '奖品3', '奖品4', '奖品5', '奖品6'],
                chatTitle: '',
                dialogVisible: false,
                isLoggedIn: false,
                userAvatar: 'img/head_img.png',
                userName: '啊实打实',
                messageList: [],
                userId: '',
                socket: '',
                messageText: '',
                roll: 30,
                cat: 0,
                area: 0,
                prizeList: [],
                lottery: {},
                loading: true,
                showLottery: false,
                lotteryRecords: [],
                recordParams:{
                    pageNo: 1,
                    pageSize: 10,
                },
                recTotal: 0,
                proName: '',
                pageNo: 1,
                pageSize: 50,
                loadingMore: false,
                total: 0
            }
        },
        created() {
            window.addEventListener('scroll', this.handleScroll);
            this.checkLoginStatus();
            this.init()
        },
        methods: {
            handleScroll() {
                let scrollEnd = this.$refs.scrollEnd;
                let scrollEndPosition = scrollEnd.getBoundingClientRect().top;
                if (scrollEndPosition <= window.innerHeight && !this.loadingMore && this.total > this.pageSize) {
                    this.loadingMore =true
                    this.pageSize += 50
                    this.init().finally(()=> {
                        this.loadingMore = false
                    });
                }
            },
            handlePageChange() {
                this.queryLottery()
            },
            handleSizeChange(e) {
                this.recordParams.pageSize = e
                this.queryLottery()
            },
            toRecord() {
                this.showLottery = true
                this.queryLottery()
            },
            async queryLottery() {
                const res = await axios.get('lottery/page',{
                    params: {
                        ...this.recordParams
                    }
                })
                this.lotteryRecords = res.data.records
                this.recTotal = res.data.total
                this.lotteryRecords.forEach(item => {
                    const date = new Date(item.createdAt);

                    // 获取日期的各个部分
                    const year = date.getFullYear();
                    const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的，所以要加1
                    const day = date.getDate().toString().padStart(2, '0');
                    const hours = date.getHours().toString().padStart(2, '0');
                    const minutes = date.getMinutes().toString().padStart(2, '0');
                    const seconds = date.getSeconds().toString().padStart(2, '0');

                    // 格式化为 yyyy-MM-dd HH:mm:ss
                    item.createdAt = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                });

            },
            // 添加滚动到底部的方法
            scrollToBottom() {
                this.$nextTick(() => {
                    const container = document.querySelector('.dialog-container');
                    if (container) {
                        container.scrollTop = container.scrollHeight;
                    }
                });
            },

            // 修改发送消息的方法
            toSendMessage() {
                if (!this.messageText.trim()) {
                    return; // 如果消息为空，不发送
                }
                const sendData = {
                    messageText: this.messageText,
                    senderId: this.userId,
                    receiverId: 1,
                };
                this.socket.send(JSON.stringify(sendData));
                this.messageText = '';
                // 发送后滚动到底部
                this.scrollToBottom();
            },
            async openSocket() {
                const res = await axios.get('/com/get')
                const self = this
                this.userId = res.data.data.id
                this.socket = new WebSocket(
                    `ws://localhost:80/message/${res.data.data.id}`
                );
                this.socket.onopen = () => {
                    console.log("WebSocket connected");
                };
                this.socket.onclose = function (e) {
                    console.log("websocket 断开:" + e.code + e.reason + e.wasClean);
                };

                this.socket.onmessage = function (event) {
                    self.messageList = JSON.parse(event.data);
                    // 在消息列表更新后，调用滚动到底部方法
                    self.scrollToBottom();
                };

                this.socket.onerror = function (error) {
                    console.error("WebSocket error:", error);
                };
            },
            // 弹出编辑窗口
            handlePwdUpdate() {
                this.formData = {};
                this.dialogFormVisiblePwd = true;
            },
            // 修改密码
            handlePwd() {
                this.$refs.dataPwdForm.validate((valid) => {
                    if (valid) {
                        axios.post("/com/updatePwd?password=" + this.formData.confirmPassword).then((res) => {
                            console.log(res.data);
                            if (res.data) {
                                this.$message({
                                    message: '恭喜你，修改成功',
                                    type: 'success'
                                });
                                this.dialogFormVisiblePwd = false;
                                this.findPage();
                            }
                        }).catch((error) => {
                            if (error == "Error: Request failed with status code 403") {
                                this.$message.error("无操作权限");
                            }
                        });
                    } else {
                        console.log('表单验证失败');
                        return false;
                    }
                });
            },
            async init() {
                try {
                    const res = await axios.get('com/products/page', {
                        params: {
                            pageNo: this.pageNo,
                            pageSize: this.pageSize,
                            name: this.proName
                        }
                    });
                    this.products = res.data.records;
                    this.total = res.data.total
                    this.prizeList = this.products.filter(item => item.isPrize === 1);
                    this.products = this.products.filter(item => item.isPrize === 0);

                } catch (error) {
                    console.error('加载产品失败:', error);
                } finally {
                    this.loading = false;
                }
            },
            // 弹出编辑窗口
            handlePwdUpdate() {
                this.formData = {};
                this.dialogFormVisiblePwd = true;
            },
            // 修改密码
            handlePwd() {
                this.$refs.dataPwdForm.validate((valid) => {
                    if (valid) {
                        axios.post("/com/updatePwd?password=" + this.formData.confirmPassword).then((res) => {
                            console.log(res.data);
                            if (res.data) {
                                this.$message({
                                    message: '恭喜你，修改成功',
                                    type: 'success'
                                });
                                this.dialogFormVisiblePwd = false;
                                this.findPage();
                            }
                        }).catch((error) => {
                            if (error == "Error: Request failed with status code 403") {
                                this.$message.error("无操作权限");
                            }
                        });
                    } else {
                        console.log('表单验证失败');
                        return false;
                    }
                });
            },
            spinWheel(random) {
                console.log(random)
                const rdm = Math.floor(10 * 3600)
                this.roll = rdm;
                this.cat = 360 / 6
            },
            async startLottery() {
                const res = await axios.get("/products/lottery")
                const {code, msg, data} = res.data
                if (code !== 200) {
                    this.$message({
                        message: msg,
                        type: 'error'
                    })
                    return
                }
                this.lottery = data
                this.spinWheel(this.lottery.randomNum)
                if (this.lottery.randomNum !== 1 ) {
                    let movedElements = this.prizeList.splice(0, this.lottery.randomNum);
                    this.prizeList.push(...movedElements);
                }
                console.log(`恭喜你，获得了${this.lottery.name}！`)
                this.$message({
                    message: `恭喜你，获得了${this.lottery.name}！`,
                    type: 'success'
                });
                setTimeout(()=> {
                    this.init()
                },5000)
            },
            openCustomerServiceChat() {
                this.chatTitle = '客服';
                this.dialogVisible = true;
                this.openSocket()
            },
            openExchangeChat() {
                this.chatTitle = '变现兑换';
                this.dialogVisible = true;
            },
            goToLogin() {
                window.location.href = 'login.html';
            },
            checkLoginStatus() {
                // 假设后端提供一个API检查登录状态
                axios.get('/com/checkLogin')
                    .then(response => {
                        if (response.data.success) {
                            this.isLoggedIn = true;
                            this.userAvatar = this.avatar;
                            this.userName = response.data.data;
                        } else {
                            this.isLoggedIn = false;
                        }
                    })
                    .catch(error => {
                        console.error('检查登录状态失败:', error);
                        this.isLoggedIn = false;
                    });
            },
            buyNow(productId) {
                window.location.href = `order-confirm.html?productId=${productId}`;
            },
            goToMyOrders() {
                window.location.href = 'my-orders.html';
            }
        }
    });
</script>
</body>

</html>